package com.cbs.java.component.application;


import java.io.*;
import java.util.Properties;
import java.util.Set;

/**
 * Created by broche on 10/13/16.
 */
public class Configs {
    private Properties configProperty = null;
    private String configFilePath;

    public Configs(Application application, String configFilePath) {
        File configFile;
        File tfile = new File(configFilePath);
        if (tfile.exists()) {
            configFile = tfile.getAbsoluteFile();
        } else {
            tfile = new File(System.getProperty("user.home") + "/.me.xuym/" + application.applicationName() + "/" + configFilePath);
            configFile = tfile.getAbsoluteFile();
        }

        this.configFilePath = configFile.getAbsolutePath();

        if (!configFile.getParentFile().exists()) {
            configFile.getParentFile().mkdirs();
        }
        if (!configFile.exists()) {
            try {
                configFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(1);
            }
        }
        InputStream inputStream = null;
        try {
            inputStream = new BufferedInputStream(new FileInputStream(configFile));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.exit(1);
        }

        configProperty = new Properties();
        try {
            configProperty.load(new InputStreamReader(inputStream, "UTF-8"));
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    public String getProperty(String key, String defaultValue) {
        return configProperty.containsKey(key) ? configProperty.getProperty(key) : defaultValue;
    }

    public int getProperty(String key, int defaultValue) {
        return configProperty.containsKey(key) ? Integer.parseInt(configProperty.getProperty(key)) : defaultValue;
    }

    public float getProperty(String key, float defaultValue) {
        return configProperty.containsKey(key) ? Float.parseFloat(configProperty.getProperty(key)) : defaultValue;
    }

    public boolean getProperty(String key, boolean defaultValue) {
        return configProperty.containsKey(key) ? Boolean.parseBoolean(configProperty.getProperty(key)) : defaultValue;
    }

    public Set<String> propertyNames() {
        return configProperty.stringPropertyNames();
    }

    public void setProperty(String key, String value) {
        configProperty.setProperty(key, value);
    }

    public void save() {
        try {
            FileWriter writer = new FileWriter(configFilePath);
            System.out.println(configFilePath);
            configProperty.store(writer, "update");
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
}
